package com.hnd.springframework.factory.support;

import cn.hutool.core.bean.BeanUtil;
import com.hnd.springframework.BeansException;
import com.hnd.springframework.PropertyValue;
import com.hnd.springframework.PropertyValues;
import com.hnd.springframework.factory.config.BeanDefinition;
import com.hnd.springframework.factory.config.BeanReference;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory {
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstanntiationStrategy();


    @Override
    Object createBean(String beanName, BeanDefinition beanDefinition, Object... args) throws BeansException {
        Object bean = createBeanInstance(beanName, beanDefinition, args);

        //属性填充
        applyPropertyValues(beanDefinition, bean, beanName);

        addSingleton(beanName, bean);

        return bean;
    }

    Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object... args) throws BeansException {
        if (args == null) {
            return instantiationStrategy.instantiate(beanDefinition, beanName, null, args);

        }
        Constructor[] constructors = beanDefinition.getBeanClass().getConstructors();
        Constructor constructorToUse = null;
        for (Constructor constructor : constructors) {
            if (constructor.getParameterTypes().length == args.length) {
                constructorToUse = constructor;
                break;
            }
        }
        return instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUse, args);
    }

    private void applyPropertyValues(BeanDefinition beanDefinition, Object bean, String BeanName) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    BeanReference beanReference = (BeanReference) value;
                    value = getBean(beanReference.getBeanName());
                }
                BeanUtil.setFieldValue(bean, name, value);

            }
        } catch (RuntimeException e) {
            throw new BeansException("初始化失败", e);
        }
    }
}
